package com.jams.goodox.utils;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;

import com.jams.goodox.TownApplicationLike;

/**
 * Created by jams on 2016/8/17.
 * ***
 * Tel: ***
 */

public class EditTextLimitUtils {
    public static void lengthFilter(final EditText editText, final int max_length,final String tips) {
        try {
            InputFilter[] filters = new InputFilter[1];
            filters[0] = new InputFilter() {
                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    int destLen = dest.length();
                    int sourceLen = source.length();
                    if (destLen + sourceLen > max_length) {
                        ToastUtil.show(TownApplicationLike.getInstance(), tips);
                        return "";
                    }
                    return source;
                }
            };
            editText.setFilters(filters);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getCharacterNum(final String content) {

        if (null == content || "".equals(content)) {

            return 0;

        } else {
            return (content.length() + getChineseNum(content));
        }
    }

    public static int getChineseNum(String s) {
        int num = 0;
        char[] myChar = s.toCharArray();
        for (int i = 0; i < myChar.length; i++) {
            if ((char) (byte) myChar[i] != myChar[i]) {
                num++;
            }
        }
        return num;
    }

    public static void lengthFilter(final Context context, final EditText editText, final int max_length,
                                    final boolean alowFace) {
        try {
            InputFilter[] filters = new InputFilter[1];
            filters[0] = new InputFilter() {
                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    int destLen = getCharacterNum(dest.toString()); // 获取字符个数(一个中文算2个字符)

                    int sourceLen = getCharacterNum(source.toString());
                    if (destLen + sourceLen > max_length) {
                        ToastUtil.show(context, "已超过可输入的最大字数");
                        return "";
                    }
                    return source;
                }
            };
            editText.setFilters(filters);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
